<?php

/**
 * 数据签名认证
 * @param  array $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
    //数据类型检测
    if (!is_array($data)) {
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 读取配置文件
 * @param string $file 调用文件
 * @return array
 */
function load_config($file) {
    $file = get_config_file($file);
    return require $file;
}

/**
 * 保存模块配置
 * @param string $file 调用文件
 * @return array
 */
function save_config($file, $config) {
    if (empty($config) || !is_array($config)) {
        return array();
    }
    $conf = load_config($file);
    $config = array_merge($conf, $config);
    $confString = var_export($config, true);
    $find = array("'true'", "'false'", "'1'", "'0'");
    $replace = array("true", "false", "1", "0");
    $confString = str_replace($find, $replace, $confString);
    $confString = "<?php \n return " . $confString . ';';
//
//
//    $conf = file_get_contents($file);
//
//    print_r($config);
//
//    //$config = array_merge($conf, $config);
//
//    //$confString = var_export($config,true);
//     //替换配置项
//
//    $conf = _replace_config($config, $conf);
//     foreach ($config as $key => $value) {
//         if (is_string($value) && !in_array($value, array('true','false'))){
//             if (!is_numeric($value)) {
//                 $value = "'" . $value . "'"; //如果是字符串，加上单引号
//             }
//         }
//         $conf = preg_replace("/'" . $key . "'\s*=\>\s*(.*?),/iU", "'".$key."'=>".$value.",", $conf);
//     }
    //写入应用配置文件
    if (file_put_contents($file, $confString)) {
        return true;
    } else {
        return false;
    }
}


/**
 * 解析配置文件路径
 * @param string $file 文件路径或简写路径
 * @return dir
 */
function get_config_file($file) {
    $name = $file;
    if (!is_file($file)) {
        $str = explode('/', $file);
        $strCount = count($str);
        switch ($strCount) {
            case 1:
                $app = APP_NAME;
                $name = $str[0];
                break;
            case 2:
                $app = $str[0];
                $name = $str[1];
                break;
        }
        $app = strtolower($app);
        if (empty($app) && empty($file)) {
            throw new \Exception("Config '{$file}' not found'", 500);
        }
        $file = APP_PATH . "{$app}/conf/{$name}.php";
        if (!file_exists($file)) {
            throw new \Exception("Config '{$file}' not found", 500);
        }
    }
    return $file;
}

/**
 * 获取所有模块Service
 * @param string $name 指定service名
 * @return array
 */
function get_all_service($name, $method, $vars = array()) {
    if (empty($name)) return null;
    $apiPath = APP_PATH . '*/service/' . $name . 'Service.php';
    $apiList = glob($apiPath);
    if (empty($apiList)) {
        return;
    }
    $appPathStr = strlen(APP_PATH);
    $method = 'get' . $method . $name;
    $data = array();
    foreach ($apiList as $value) {
        $path = substr($value, $appPathStr, -4);
        $path = str_replace('\\', '/', $path);
        $appName = explode('/', $path);
        $appName = $appName[0];
        $config = load_config($appName . '/config');
        if (!$config['APP_SYSTEM'] && (!$config['APP_STATE'] || !$config['APP_INSTALL'])) {
            continue;
        }
        $class = '\\app\\' . $appName . '\\' . 'service' . '\\' . $name . 'Service';
        if (!class_exists($class)) {
            return;
        }
        $class = target($appName . '/' . $name, 'service');
        if (method_exists($class, $method)) {
            $data[$appName] = $class->$method($vars);
        }
    }
    return $data;
}

/**
 * 获取指定模块Service
 * @param string $name 指定service名
 * @return Service
 */
function service($appName, $name, $method, $vars = array()) {
    $config = load_config($appName . '/config');
    if (!$config['APP_SYSTEM'] && (!$config['APP_STATE'] || !$config['APP_INSTALL'])) {
        return;
    }
    $class = '\\app\\' . $appName . '\\' . 'service' . '\\' . $name . 'Service';
    if (!class_exists($class)) {
        return;
    }
    $class = target($appName . '/' . $name, 'service');
    if (method_exists($class, $method)) {
        return $class->$method($vars);
    }
}

/**
 * 调用指定模块的API
 * @param string $name 指定api名
 * @return Api
 */
function api($appName, $name, $method, $vars = array()) {
    $config = load_config($appName . '/config');
    if (!$config['APP_SYSTEM'] && (!$config['APP_STATE'] || !$config['APP_INSTALL'])) {
        return;
    }
    $class = '\\app\\' . $appName . '\\' . 'api' . '\\' . $name . 'Api';
    if (!class_exists($class)) {
        return;
    }
    $class = target($appName . '/' . $name, 'api');
    if (method_exists($class, $method)) {
        return $class->$method($vars);
    }
}

/**
 * 字符串截取(别名函数)
 */
function len($str, $len = 0) {
    return str_len($str, $len);
}

/**
 * 截取摘要
 */
function get_text_make($data, $cut = 0, $str = "...") {
    $data = strip_tags($data);
    $pattern = "/&[a-zA-Z]+;/";
    $data = preg_replace($pattern, '', $data);
    if (!is_numeric($cut)) {
        return $data;
    }
    if ($cut > 0) {
        $data = mb_strimwidth($data, 0, $cut, $str);
    }
    return $data;
}

/**
 * 语言替换
 */
function lang($str) {
    return \variant\ext\Lang::get($str);
}

//图片裁剪
function cut_image($img, $width, $height, $type = 2) {
    if (empty($width) && empty($height)) {
        return $img;
    }
    $imgDir = realpath(BASE_PATH . $img);
    if (!is_file($imgDir)) {
        return $img;
    }
    $imgInfo = pathinfo($img);
    $newImg = $imgInfo['dirname'] . '/cut_' . $width . '_' . $height . '_' . $imgInfo["basename"];
    $newImgDir = BASE_PATH . $newImg;
    if (!is_file($newImgDir)) {
        $image = new \variant\ext\Image($imgDir);
        if($image->thumb($width, $height, $type)->output($newImgDir) === false){
            return $img;
        }
    }
    return $newImg;

}